
var galleryTop;// Swiper
var gDispState = 0;// 0:pause, 1:play
var gAutoTimer;// slide timeout
var gPlayer = null;
var gWHScale=2/3;// 视频宽高比
var gH = 200;// 视频当前高
var DISP_DURATION = 4000;// 每页默认显示时长
var DELAY_1 = 400;// 延迟1
var MediaPos = Number(gMediaPos) || 3;

$(function(){
    // 遮罩层
    //var maskCanv=document.getElementById('screen_mask');
    //var maskCanv2=document.getElementById('load_mask');

    // swiper初始化
    galleryTop = new Swiper('.gallery-top', {
        direction: 'horizontal',
        pagination: '.swiper-pagination',
        paginationClickable: true,
        paginationBulletRender: function (index, className) {
            // 自定义分页器：加页码
            return '<div class="' + className + '">' + (index + 1) + '</div>';
        },
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',
        slidesPerView: 'auto',
        spaceBetween: 15,
        onInit: function(swiper){
            // TODO
        },
        onImagesReady: function(swiper){
            // 图片加载完毕后按照图片尺寸设置canvas位置
            initMedia(swiper);
        },
        onTouchStart: function(swiper,even){
            // 碰触到slider时
        },
        onSlideChangeEnd: function(swiper){// 滑动／翻页结束后
            // 清除自动翻页
            if (gAutoTimer) {
                clearTimeout(gAutoTimer);
            }

            // 清除canvas
            $(".video").addClass("display_hide");
            clearCanv();

            if (gDispState == 1) {// play
                if (gMediaFlg == 1) {
                    musicOFF();
                    var t = gPlayer.cache(swiper.activeIndex,function(ret){
                        if (ret == 1) {// RET_ERROR
                            // TODO
                        }
                    });
                    if (t == 1){
                        musicON(DELAY_1, 0);
                    } else {
                        autoSlide(DISP_DURATION);
                    }

                } else {
                    autoSlide(DISP_DURATION);
                }
            } else {// pause
                musicOFF();
            }
        }
    });

    //var galleryThumbs = new Swiper('.gallery-thumbs', {
    //    spaceBetween: 10,
    //    centeredSlides: true,
    //    slidesPerView: 'auto',
    //    touchRatio: 0.2,
    //    slideToClickedSlide: true
    //});
    //galleryTop.params.control = galleryThumbs;
    //galleryThumbs.params.control = galleryTop;
});


function initMedia(swiper){
    if (gPlayer) {
        return;
    }

    gPlayer = new SJGMediaPlayer("vid_canv");
    var wh = gPlayer.init(gPagesJson);
    if (wh) {
        // 设定canvas尺寸
        gWHScale = wh.w / wh.h;
        var vidCanv = document.getElementById('vid_canv');
        var vidCont = vidCanv.getContext('2d');

        // 缩放视频到指定大小
        var tmpH = document.body.clientHeight*0.45;// 默认高度为屏幕高度一半
        var curImg = null;
        if (swiper) {
            // 如果图像已加载，则取图像高度的一半
            curImg = document.getElementById('img' + swiper.activeIndex);
            if (curImg) {
                tmpH = curImg.height * 0.5;
            }
        }
        gH = wh.h;
        //var s = tmpH/wh.h;
        vidCanv.height = tmpH;
        vidCanv.width = tmpH * gWHScale;
        //vidCont.scale(s,s);

        // 设定视频位置
        setMediaPos(vidCanv, curImg);
    }
}

function setMediaPos(vidCanv, imgObj){
    // 设定视频位置
    var vidDiv = document.getElementById('video');
    var top = 0;
    var left = 0;
    if (MediaPos == 5) {
        // 位移到图像中心
        top = (document.body.clientHeight - vidCanv.height) * 0.5;
        left = (document.body.clientWidth - vidCanv.width) * 0.5;

    } else {
        // 位移到图像右下角(边距10px)
        var top = document.body.clientHeight * 0.5 - 10;
        var left = document.body.clientWidth - vidCanv.width - 10;
        if (imgObj) {
            // 如果图像已加载，则按照图像对齐
            left = document.body.clientWidth * 0.5 + imgObj.width * 0.5 - vidCanv.width - 10;
        }
    }
    vidDiv.style.top = top + "px";
    vidDiv.style.left = left + "px";
    vidDiv.style.width = vidCanv.width + "px";
    vidDiv.style.height = vidCanv.height + "px";
}

function onClickMake(){
    window.location.href = gAPIHOST+'/preview/makeCard';
}
function onClickDisplay(){
    if (gAutoTimer) {
        clearTimeout(gAutoTimer);
    }
    gDispState = 1;
    $(".icon-music").removeClass("music_play");
    $(".icon-music").addClass("music_pause");
    $(".mask").addClass("display_hide");

    // 返回第一页
    if (galleryTop && galleryTop.activeIndex>0){
        galleryTop.slideTo(0);
        return;
    }

    //gMediaFlg = 1;// 默认播放音视频
    if (gMediaFlg == 1) {
        // 如果未在 onImagesReady 初始化 SJGMediaPlayer
        // 则按照窗口尺寸设置canvas位置
        if (gPlayer == null) {
            initMedia(null);
        }

        // loading遮罩层
        var playFlg = null;
        $(".mask2").removeClass("display_hide");
        var t = gPlayer.cache(0,function(ret){
            $(".mask2").addClass("display_hide");
            if (playFlg == null) {
                playFlg = 1;
                if (t == 0 || ret == 1){
                    autoSlide(DISP_DURATION);
                } else {
                    musicON(DELAY_1, 0);
                }
            }
        });

        // 等待30秒，若loading未成功则改为仅播放普通文档模式
        var wait = setTimeout(function(){
            $(".mask2").addClass("display_hide");
            if (playFlg == null) {
                playFlg = 1;
                if (gAutoTimer) {
                    clearTimeout(gAutoTimer);
                }
                gMediaFlg = 0;
                autoSlide(DISP_DURATION);
            }
        },30000);

    } else {
        autoSlide(DISP_DURATION);
    }
}

function doDisp(){
    if (gAutoTimer) {
        clearTimeout(gAutoTimer);
    }
    gDispState = 1;
    $(".icon-music").removeClass("music_play");
    $(".icon-music").addClass("music_pause");
    $(".mask").addClass("display_hide");

    // 返回第一页
    if (galleryTop && galleryTop.activeIndex>0){
        galleryTop.slideTo(0);
        return;
    }

    if (gMediaFlg == 1) {
        // 如果未在 onImagesReady 初始化 SJGMediaPlayer
        // 则按照窗口尺寸设置canvas位置
        if (gPlayer == null) {
            initMedia(null);
        }

        // loading遮罩层
        $(".mask2").removeClass("display_hide");
        var t = gPlayer.cache(0,function(ret){
            $(".mask2").addClass("display_hide");
            if (t == 0 || ret == 1){
                autoSlide(DISP_DURATION);
            } else {
                musicON(DELAY_1, 0);
            }
        });

    } else {
        autoSlide(DISP_DURATION);
    }
}
/**
 * 播放文稿
 */
function onClickDispDoc(){
    gMediaFlg = 0;
    doDisp();
}
/**
 * 播放多媒体
 */
function onClickDispMedia(){
    gMediaFlg = 1;
    doDisp();
}
function setReplayMask(){
    if (gAutoTimer) {
        clearTimeout(gAutoTimer);
    }

    gDispState = 0;
    $(".icon-music").removeClass("music_pause");
    $(".icon-music").addClass("music_play");

    $(".disp_play").addClass("display_hide");
    $(".disp_replay").removeClass("display_hide");

    $(".mask").removeClass("display_hide");
}

/**
 * 自动延迟换页
 */
function autoSlide(delay){
    if (gAutoTimer) {
        clearTimeout(gAutoTimer);
    }

    if (gDispState == 1) {// play
        gAutoTimer = setTimeout(function(){
            if (galleryTop) {
                if (galleryTop.isEnd) {
                    // 最后一页
                    setReplayMask();
                } else {
                    galleryTop.slideNext();
                }
            }
        },delay);
    }
}

var resizeEnd;
function redrawCanv() {
    if (resizeEnd) {
        clearTimeout(resizeEnd);
    }
    resizeEnd = setTimeout(function(){
        var vidCanv = document.getElementById('vid_canv');
        var vidCont=vidCanv.getContext('2d');

        var tmpH = document.body.clientHeight*0.45;// 默认高度为屏幕高度一半
        var curImg = null;
        if (galleryTop) {
            // 如果图像已加载，则取图像高度的一半
            curImg = document.getElementById('img' + galleryTop.activeIndex);
            if (curImg) {
                tmpH = curImg.height * 0.5;
            }
        }
        //var s = tmpH/gH;
        //gH = tmpH;
        vidCont.clearRect(0,0, vidCanv.width, vidCanv.height);
        vidCanv.height = tmpH;
        vidCanv.width = tmpH*gWHScale;
        //vidCont.scale(s,s);

        // 设定视频位置
        setMediaPos(vidCanv, curImg);

    },300);
}

// update on any window size change.
window.addEventListener("resize", redrawCanv);

/**
 * play/pause 控制按钮
 */
function onMusicClick(){
    if(gDispState == 1){// 点击前为play
        if (gAutoTimer) {
            clearTimeout(gAutoTimer);
        }

        gDispState = 0;
        $(".icon-music").removeClass("music_pause");
        $(".icon-music").addClass("music_play");
        musicOFF();

    }else{// 点击前为pause
        gDispState = 1;
        $(".icon-music").removeClass("music_play");
        $(".icon-music").addClass("music_pause");

        if (gMediaFlg == 1) {
            var t = gPlayer.cache(galleryTop.activeIndex,function(ret){
                if (ret == 1) {// RET_ERROR
                    // TODO
                }
            });
            if (t == 1){
                musicON(DELAY_1, 1);// 恢复play
            } else {
                autoSlide(DISP_DURATION);
            }

        } else {
            autoSlide(DISP_DURATION);
        }
    }
}

function onMusicEnded(){
    if(galleryTop){
        musicOFF();
        autoSlide(DELAY_1);
    }
}

/**
 * @param delayTime
 * @param flg: 0重新播放, 1继续播放
 */
function musicON(delayTime,flg) {
    if (gMediaFlg) {
        setTimeout(function(){

            if (gPagesJson && gPagesJson.length>0
                && gPagesJson[galleryTop.activeIndex].video
                && gPagesJson[galleryTop.activeIndex].video.length>0) {
                // 有视频时显示canvas
                //$(".video").removeClass("display_hide");
            }

            gPlayer.play(galleryTop.activeIndex,flg,
                function(ret){
                    $(".mask2").addClass("display_hide");
                    if (ret == 1){// RET_ERROR
                        $(".video").addClass("display_hide");
                        clearCanv();
                        autoSlide(DISP_DURATION);
                    } else {
                        $(".video").addClass("display_hide");
                        clearCanv();
                        autoSlide(DELAY_1);
                    }
                });
        },delayTime);
    }
}
function musicOFF() {
    if (gMediaFlg) {
        gPlayer.pause();
    }
}

function clearCanv() {
    var canv=document.getElementById('vid_canv');
    var cont=canv.getContext('2d');
    var maxH = document.body.clientHeight/2;
    cont.clearRect(0,0,maxH*gWHScale,maxH);// 按最大范围clear
}

/**
 * 视频
 */
//$("#vid").bind('play',function(){
//    var canvas=document.getElementById('canv');
//    var context=canvas.getContext('2d');
//    var cw = Math.floor(canvas.clientWidth / 1);
//    var ch = Math.floor(canvas.clientHeight / 1);
//    canvas.width = cw;
//    canvas.height = ch;
//    draw(this,context,cw,ch);
//});
//function draw(v,c,w,h) {
//   // var currentTime = (Math.round(parseFloat(v.currentTime)*10000)/10000);
//   // var duration = (Math.round(parseFloat(v.duration)*10000)/10000);
//    if( v.ended ) return false;
//
//    c.drawImage(v,0,0,w,h);
//    setTimeout(draw,30,v,c,w,h);
//}

wx.ready(function () {
    // 自定义分享内容及分享结果接口

    var myData = {
        title: gWechat.title,
        desc: gWechat.desc,
        link: gURL,
        imgUrl: gShareIcon,
        trigger: function (res) {
            // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，
            // 因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回
            //alert('用户点击发送给朋友');
        },
        success: function (res) {
            alert('已分享');
        },
        cancel: function (res) {
            alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    };

    // 监听“分享给朋友”
    wx.onMenuShareAppMessage(myData);
    // 监听“分享到朋友圈”
    wx.onMenuShareTimeline(myData);

});

wx.error(function (res) {
    //alert(res.errMsg);
});